package cn.xiaobai.v3;

import cn.xiaobai.http.Request;
import cn.xiaobai.http.Response;
import cn.xiaobai.utils.LoggerFactory;
import cn.xiaobai.web.TestController;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * servlet 的 http 请求处理
 *
 * @Author yangdaji
 * @Date 2023/11/29
 * @PackageName cn.xiaobai.v3
 * @ClassName HttpServlet
 */
public abstract class HttpServlet extends GenericServlet {


    static LoggerFactory.Logger log = LoggerFactory.getLogger(HttpHandler3.class);


    @Override
    public void service(Request request, Response response) throws IOException {
        // 请求经过该方法进行分配
        if ("get".equalsIgnoreCase(request.getMethod())) {
            doGet(request, response);
        } else if ("post".equalsIgnoreCase(request.getMethod())) {
            doPost(request, response);
        }
    }


    // 由子类重写
    protected void doGet(Request request, Response response) {

        String uri = request.getUri();
        TestController controllerBean = TomcatFactory.getControllerBean(uri, TestController.class);
        Class<? extends TestController> beanClass = controllerBean.getClass();
        Method[] declaredMethods = beanClass.getDeclaredMethods();
        Object[] values = request.getParameterMapping().values().toArray();

        try {
            for (Method method : declaredMethods) {
                if (method.getReturnType() != Void.class) {
                    Object result = method.invoke(controllerBean, values);
                    response.setBody(result.toString());
                } else {
                    method.invoke(controllerBean, values);
                }
            }

            // 获取返回结果, 写入
            response.write();
        } catch (IOException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
            e.printStackTrace();
            response.setBody("<body> 500 Parameter error </body>");
            try {
                response.write();
            } catch (IOException ex) {
                e.printStackTrace();
            }
        }

    }

    protected void doPost(Request request, Response response) {
        // 暂时测试 get 请求
        doGet(request, response);
    }


}
